// Copyright Epic Games, Inc. All Rights Reserved.

#include "SmartCore.h"
#include "IPythonScriptPlugin.h"
#include "Misc/Paths.h"
#include "Interfaces/IPluginManager.h"

// 分割字符串
// void USmartCore::StringSplit(FString& SrcStr, const FString& TagStr, TArray<FString>& result)
// {
// 	if (SrcStr.Contains(TagStr))
// 	{
// 		FString left;
// 		FString right;
// 		SrcStr.Split(TagStr, &left, &right);
// 		if (!result.Contains(left))
// 		{
// 			result.Add(left);
// 		}
// 		StringSplit(right, TagStr, result);
// 	}
// 	else
// 	{
// 		if (!result.Contains(*SrcStr))
// 		{
// 			result.Add(*SrcStr);
// 		}
// 	}
// }

void USmartCore::UserScript()
{
	TArray<FString> configPaths;
	//configPaths.Add(FPaths::ProjectConfigDir());
	configPaths.Add(FPaths::ProjectContentDir() / TEXT("Python"));
	configPaths.Add(IPluginManager::Get().FindPlugin("SmartStudio")->GetContentDir() / TEXT("Python"));
	{
		FString env_name = "UNREAL_SMART_STARTUP_PYTHON_PATH";
		FString confgi_str = FPlatformMisc::GetEnvironmentVariable(*env_name);
		if (!confgi_str.IsEmpty())
		{
			StringSplit(confgi_str, ";", configPaths);
		}
	}
	for (FString _path : configPaths)
	{
		TArray<FString> FoundFiles;
		FString FileEx = ".py";
		IFileManager::Get().FindFiles(FoundFiles, *_path, *FileEx);
		if (FoundFiles.Num() > 0)
		{
			for (FString FileName : FoundFiles)
			{
				FString FilePath = _path + "/" + FileName;
				if (FPaths::FileExists(FilePath))
				{
					FPythonCommandEx PythonCommand;
					PythonCommand.Command = *FilePath;
					PythonCommand.ExecutionMode = EPythonCommandExecutionMode::ExecuteFile;
					IPythonScriptPlugin::Get()->ExecPythonCommandEx(PythonCommand);
				}
			}
		}
	}
}
